import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import Header from './Header';
import PhotoPreview from './PhotoPreview';
import aiVideoService from '../services/aiVideoService';
import { isVideoTokenConfigured } from '../services/aiVideoConfigService';
import AIVideoConfig from './AIVideoConfig';
import './AIVideoGenerator.css';

const AIVideoGenerator = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);
  const [photos, setPhotos] = useState([]);
  const [videoOptions, setVideoOptions] = useState({
    duration: 10,
    style: 'cinematic',
    quality: 'high',
    music: 'auto',
    transition: 'fade',
    description: ''
  });
  const [generationStatus, setGenerationStatus] = useState(null);
  const [generatedVideos, setGeneratedVideos] = useState([]);
  const [showPhotoPreview, setShowPhotoPreview] = useState(false);
  const [previewPhotoIndex, setPreviewPhotoIndex] = useState(0);
  const [videoStyles, setVideoStyles] = useState([]);
  const [musicOptions, setMusicOptions] = useState([]);
  const [activeTab, setActiveTab] = useState('create'); // 'create' or 'history'
  const [showAIVideoConfig, setShowAIVideoConfig] = useState(false);
  const [tokenConfigured, setTokenConfigured] = useState(false);

  // Check for mock authentication
  const isAuthenticated = !!localStorage.getItem('mockAuthToken');
  const user = isAuthenticated ? JSON.parse(localStorage.getItem('mockUser') || '{}') : null;

  useEffect(() => {
    // Check if AI video token is configured
    setTokenConfigured(isVideoTokenConfigured());
    
    // Load video styles and music options
    const mockVideoStyles = [
      { id: 'cinematic', name: '电影风格', description: '专业的电影级视觉效果' },
      { id: 'animated', name: '动画风格', description: '活泼的动画效果' },
      { id: 'slideshow', name: '幻灯片风格', description: '简洁的幻灯片展示' },
      { id: 'vintage', name: '复古风格', description: '怀旧复古的视觉效果' },
      { id: 'modern', name: '现代风格', description: '时尚现代的视觉效果' }
    ];
    
    const mockMusicOptions = [
      { id: 'auto', name: '自动选择', description: '根据照片内容自动匹配音乐' },
      { id: 'none', name: '无音乐', description: '不添加背景音乐' },
      { id: 'upbeat', name: '欢快', description: '轻快活泼的背景音乐' },
      { id: 'calm', name: '平静', description: '舒缓平静的背景音乐' },
      { id: 'epic', name: '史诗', description: '宏大壮观的背景音乐' },
      { id: 'romantic', name: '浪漫', description: '浪漫温馨的背景音乐' }
    ];
    
    setVideoStyles(mockVideoStyles);
    setMusicOptions(mockMusicOptions);
    
    // Load user's video history from localStorage
    const userVideos = JSON.parse(localStorage.getItem('userGeneratedVideos') || '[]');
    setGeneratedVideos(userVideos);
  }, []);

  const handleConfigSaved = () => {
    setTokenConfigured(isVideoTokenConfigured());
  };

  const handlePhotoUpload = (e) => {
    const files = Array.from(e.target.files);
    
    // Create promises to read each file as a data URL
    const filePromises = files.map((file, index) => {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = (event) => {
          resolve({
            id: Date.now() + index,
            name: file.name,
            thumbnail: event.target.result,
            file: file // Store the file object for later use
          });
        };
        reader.readAsDataURL(file);
      });
    });
    
    // Wait for all files to be read
    Promise.all(filePromises).then(photoList => {
      setPhotos([...photos, ...photoList]);
    });
  };

  const handleRemovePhoto = (photoId) => {
    setPhotos(photos.filter(photo => photo.id !== photoId));
  };

  const handlePhotoPreview = (photo, index) => {
    setPreviewPhotoIndex(index);
    setShowPhotoPreview(true);
  };

  const handleClosePhotoPreview = () => {
    setShowPhotoPreview(false);
  };

  const handleOptionChange = (option, value) => {
    setVideoOptions(prev => ({
      ...prev,
      [option]: value
    }));
  };

  const handleGenerateVideo = async () => {
    if (photos.length === 0) {
      alert(t('ai.selectPhotos'));
      return;
    }

    setIsLoading(true);
    setGenerationStatus({ status: 'processing', progress: 0 });

    try {
      // Prepare photo data for API
      const photoData = photos.map(photo => ({
        id: photo.id,
        name: photo.name,
        thumbnail: photo.thumbnail
      }));

      // Simulate video generation with progress updates
      let progress = 0;
      const progressInterval = setInterval(() => {
        progress += Math.random() * 15;
        if (progress >= 100) {
          progress = 100;
          clearInterval(progressInterval);
        }
        setGenerationStatus({
          status: progress < 100 ? 'processing' : 'completed',
          progress: Math.floor(progress),
          estimatedTimeRemaining: progress < 100 ? `${Math.floor((100 - progress) / 10)} 秒` : '0 秒'
        });
      }, 500);

      // Call AI video service to generate video
      const result = await aiVideoService.generateVideoFromPhotos(photoData, videoOptions);
      
      // Add the new video to the list
      const newVideo = {
        id: result.taskId,
        name: `视频_${new Date().toLocaleDateString()}`,
        thumbnail: result.thumbnail,
        videoUrl: result.videoUrl,
        duration: result.duration,
        size: result.size,
        createdAt: result.createdAt,
        photos: photoData,
        options: videoOptions
      };

      const updatedVideos = [newVideo, ...generatedVideos];
      setGeneratedVideos(updatedVideos);
      
      // Save to localStorage
      localStorage.setItem('userGeneratedVideos', JSON.stringify(updatedVideos));
      
      // Clear the form
      setPhotos([]);
      setVideoOptions({
        duration: 10,
        style: 'cinematic',
        quality: 'high',
        music: 'auto',
        transition: 'fade',
        description: ''
      });
      
      alert(t('ai.videoGenerated'));
    } catch (error) {
      console.error('Error generating video:', error);
      alert(t('ai.videoGenerationError'));
    } finally {
      setIsLoading(false);
      setGenerationStatus(null);
    }
  };

  const handleDeleteVideo = (videoId) => {
    if (window.confirm(t('ai.deleteVideoConfirmation'))) {
      const updatedVideos = generatedVideos.filter(video => video.id !== videoId);
      setGeneratedVideos(updatedVideos);
      localStorage.setItem('userGeneratedVideos', JSON.stringify(updatedVideos));
    }
  };

  const handleDownloadVideo = (video) => {
    // Create a temporary link element to download the video
    const link = document.createElement('a');
    link.href = video.videoUrl;
    link.download = `${video.name}.mp4`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const handlePlayVideo = (video) => {
    // Find the video element and play it
    const videoElement = document.querySelector(`[data-video-id="${video.id}"]`);
    if (videoElement) {
      const playPromise = videoElement.play();
      
      if (playPromise !== undefined) {
        playPromise.then(_ => {
          // Video started playing successfully
        })
        .catch(error => {
          // Auto-play was prevented or interrupted
          console.error('Video play error:', error);
          // Try to pause first, then play again
          videoElement.pause();
          setTimeout(() => {
            videoElement.play().catch(e => console.error('Retry play error:', e));
          }, 100);
        });
      }
    }
  };

  if (!isAuthenticated) {
    navigate('/auth');
    return null;
  }

  return (
    <div className="ai-video-generator-container">
      <Header />
      <div className="ai-video-generator-content">
        <div className="ai-video-generator-header">
          <h1 className="ai-video-generator-title">{t('ai.title')}</h1>
          <p className="ai-video-generator-subtitle">{t('ai.subtitle')}</p>
          {!tokenConfigured && (
            <div className="token-warning">
              <span className="warning-icon">⚠️</span>
              <span>{t('ai.tokenRequired')}</span>
              <button
                className="config-btn"
                onClick={() => setShowAIVideoConfig(true)}
              >
                {t('aiVideoConfig.title')}
              </button>
            </div>
          )}
        </div>

        {/* Tab Navigation */}
        <div className="tab-navigation">
          <button
            className={`tab-btn ${activeTab === 'create' ? 'active' : ''}`}
            onClick={() => setActiveTab('create')}
          >
            {t('ai.createVideo')}
          </button>
          <button
            className={`tab-btn ${activeTab === 'history' ? 'active' : ''}`}
            onClick={() => setActiveTab('history')}
          >
            {t('ai.videoHistory')}
          </button>
        </div>

        {activeTab === 'create' ? (
          // Create Video Tab
          <div className="create-video-tab">
            {/* Photo Upload Section */}
            <div className="photo-upload-section">
              <h2>{t('ai.selectPhotos')}</h2>
              <div className="upload-area">
                <input
                  type="file"
                  id="photo-upload"
                  multiple
                  accept="image/*"
                  onChange={handlePhotoUpload}
                  style={{ display: 'none' }}
                />
                <label htmlFor="photo-upload" className="upload-label">
                  <div className="upload-icon">📷</div>
                  <p>{t('ai.clickToUpload')}</p>
                  <p>{t('ai.orDragDrop')}</p>
                </label>
              </div>
              
              {photos.length > 0 && (
                <div className="selected-photos">
                  <h3>{t('ai.selectedPhotos')} ({photos.length})</h3>
                  <div className="photo-grid">
                    {photos.map((photo, index) => (
                      <div key={photo.id} className="photo-item">
                        <div className="photo-thumbnail" onClick={() => handlePhotoPreview(photo, index)}>
                          <img src={photo.thumbnail} alt={photo.name} />
                        </div>
                        <button 
                          className="remove-photo-btn" 
                          onClick={() => handleRemovePhoto(photo.id)}
                          title={t('ai.removePhoto')}
                        >
                          ×
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Video Description Section */}
            <div className="video-description-section">
              <h2>{t('ai.videoDescription')}</h2>
              <div className="description-input-group">
                <textarea
                  id="video-description"
                  value={videoOptions.description}
                  onChange={(e) => handleOptionChange('description', e.target.value)}
                  placeholder={t('ai.videoDescriptionPlaceholder')}
                  rows={3}
                  className="description-textarea"
                />
                <div className="field-help">
                  {t('ai.videoDescriptionHelp')}
                </div>
              </div>
            </div>

            {/* Video Options Section */}
            <div className="video-options-section">
              <h2>{t('ai.videoOptions')}</h2>
              <div className="options-grid">
                <div className="option-group">
                  <label htmlFor="duration">{t('ai.duration')} (秒)</label>
                  <input
                    type="range"
                    id="duration"
                    min="5"
                    max="30"
                    value={videoOptions.duration}
                    onChange={(e) => handleOptionChange('duration', parseInt(e.target.value))}
                  />
                  <span className="option-value">{videoOptions.duration}秒</span>
                </div>

                <div className="option-group">
                  <label htmlFor="style">{t('ai.style')}</label>
                  <select
                    id="style"
                    value={videoOptions.style}
                    onChange={(e) => handleOptionChange('style', e.target.value)}
                  >
                    {videoStyles.map(style => (
                      <option key={style.id} value={style.id}>
                        {style.name}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="option-group">
                  <label htmlFor="quality">{t('ai.quality')}</label>
                  <select
                    id="quality"
                    value={videoOptions.quality}
                    onChange={(e) => handleOptionChange('quality', e.target.value)}
                  >
                    <option value="low">{t('ai.lowQuality')}</option>
                    <option value="medium">{t('ai.mediumQuality')}</option>
                    <option value="high">{t('ai.highQuality')}</option>
                  </select>
                </div>

                <div className="option-group">
                  <label htmlFor="music">{t('ai.music')}</label>
                  <select
                    id="music"
                    value={videoOptions.music}
                    onChange={(e) => handleOptionChange('music', e.target.value)}
                  >
                    {musicOptions.map(option => (
                      <option key={option.id} value={option.id}>
                        {option.name}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="option-group">
                  <label htmlFor="transition">{t('ai.transition')}</label>
                  <select
                    id="transition"
                    value={videoOptions.transition}
                    onChange={(e) => handleOptionChange('transition', e.target.value)}
                  >
                    <option value="fade">{t('ai.fadeTransition')}</option>
                    <option value="slide">{t('ai.slideTransition')}</option>
                    <option value="zoom">{t('ai.zoomTransition')}</option>
                  </select>
                </div>
              </div>
            </div>

            {/* Generate Button */}
            <div className="generate-section">
              <button
                className="generate-btn"
                onClick={handleGenerateVideo}
                disabled={isLoading || photos.length === 0}
              >
                {isLoading ? (
                  <span className="loading-spinner"></span>
                ) : (
                  t('ai.generateVideo')
                )}
              </button>
            </div>

            {/* Generation Status */}
            {generationStatus && (
              <div className="generation-status">
                <h3>{t('ai.generationStatus')}</h3>
                <div className="progress-bar">
                  <div 
                    className="progress-fill" 
                    style={{ width: `${generationStatus.progress}%` }}
                  ></div>
                </div>
                <p>{t('ai.progress')}: {generationStatus.progress}%</p>
                {generationStatus.estimatedTimeRemaining && (
                  <p>{t('ai.estimatedTime')}: {generationStatus.estimatedTimeRemaining}</p>
                )}
              </div>
            )}
          </div>
        ) : (
          // Video History Tab
          <div className="video-history-tab">
            <h2>{t('ai.videoHistory')}</h2>
            {generatedVideos.length > 0 ? (
              <div className="video-list">
                {generatedVideos.map(video => (
                  <div key={video.id} className="video-item">
                    <div className="video-thumbnail">
                      {video.videoUrl ? (
                        <>
                          <video
                            poster={video.thumbnail}
                            className="video-player"
                            preload="metadata"
                            data-video-id={video.id}
                            onClick={() => handlePlayVideo(video)}
                          >
                            <source src={video.videoUrl} type="video/mp4" />
                            您的浏览器不支持视频播放
                          </video>
                          <div className="video-play-overlay">
                            <div className="video-play-icon">▶️</div>
                          </div>
                        </>
                      ) : (
                        <img src={video.thumbnail} alt={video.name} />
                      )}
                    </div>
                    <div className="video-info">
                      <h3 className="video-name">{video.name}</h3>
                      <p className="video-details">
                        {t('ai.duration')}: {video.duration}秒 | {t('ai.size')}: {video.size}
                      </p>
                      <p className="video-date">{t('ai.createdAt')}: {new Date(video.createdAt).toLocaleString()}</p>
                    </div>
                    <div className="video-actions">
                      {video.videoUrl && (
                        <button
                          className="video-action-btn"
                          onClick={(e) => {
                            e.stopPropagation();
                            handlePlayVideo(video);
                          }}
                          title={t('ai.playVideo')}
                        >
                          ▶️
                        </button>
                      )}
                      <button
                        className="video-action-btn"
                        onClick={() => handleDownloadVideo(video)}
                        title={t('ai.downloadVideo')}
                      >
                        ⬇️
                      </button>
                      <button
                        className="video-action-btn delete"
                        onClick={() => handleDeleteVideo(video.id)}
                        title={t('ai.deleteVideo')}
                      >
                        🗑️
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="no-videos">
                <div className="no-videos-icon">🎬</div>
                <h3>{t('ai.noVideos')}</h3>
                <p>{t('ai.noVideosMessage')}</p>
                <button 
                  className="create-first-video-btn"
                  onClick={() => setActiveTab('create')}
                >
                  {t('ai.createFirstVideo')}
                </button>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Photo Preview Modal */}
      {showPhotoPreview && (
        <PhotoPreview
          photos={photos}
          currentIndex={previewPhotoIndex}
          onClose={handleClosePhotoPreview}
        />
      )}
      
      {showAIVideoConfig && (
        <AIVideoConfig
          onClose={() => setShowAIVideoConfig(false)}
          onConfigSaved={handleConfigSaved}
        />
      )}
    </div>
  );
};

export default AIVideoGenerator;